<?php

require_once 'Zend/Form/Element/Text.php';

class ZFKiller_Form_Element_Date extends Zend_Form_Element_Text {

    public function __construct($spec, $options = null) {
        ZFKiller_Form_Element::formatDefaultOptions($spec, $options);
        parent::__construct($spec, $options);

        ZFKiller_Form_Element::formatElementAsDate($this);
        //$this->addValidators(array('Date'));
    }

    public function getValue() {
        switch (ZFKiller_Form::getValueType()) {
            case ZFKiller_Form::GET_VALUE_TYPE_DB:
                return $this->getValueDb();
                break;
            case ZFKiller_Form::GET_VALUE_TYPE_USER:
                return $this->getValueUser();
                break;
            default:
                return $this->getValueUser();
                //return $this->getUnfilteredValue();
                break;
        }
    }

    public function getValueDb() {
        $date = $this->getUnfilteredValue();
        if ($date instanceof Zend_Date) {
            $date = new Zend_Date($this->getUnfilteredValue(), Zend_Locale_Format::getDateFormat());
            return $date->toString('YYYY-MM-dd HH:mm:ss');
        }
        return null;
    }

    public function getValueUser() {
        $date = $this->getUnfilteredValue();
        if (!$date instanceof Zend_Date) {
            $date = new Zend_Date($this->getUnfilteredValue(), Zend_Locale_Format::getDateFormat());
        }
        return $date->get(Zend_Date::DATES);
    }

    public function setValue($date) {
        if (!$date instanceof Zend_Date) {
            try {
                if (is_int($date)) {
                    $date = new Zend_Date($date);
                }
                else {
                    $date = new Zend_Date($date, Zend_Locale_Format::getDateFormat(Zend_Registry::get('Zend_Locale')));
                }
                parent::setValue($date);
            } catch (Zend_Date_Exception $e) {
                
            }
        }

        return $this;
    }

}